<template>
  <div class="alloc-menu">
    <el-card>
      <el-tree
        ref="menu-tree"
        node-key="id"
        :default-checked-keys="checkedKeys"
        :data="menu"
        :props="defaultProps"
        show-checkbox
        default-expand-all
      ></el-tree>
      <div style="margin: 20px">
        <el-button @click="onReset">清空</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMenuList, setMenuList, getRoleMenus } from '@/services/menu'

export default {
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [Number, String],
      require: true
    }
  },
  data () {
    return {
      menu: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: []
    }
  },
  created () {
    this.getListMenu()
    this.loadRoleMenu()
  },
  methods: {
    onReset () {
      this.$refs['menu-tree'].setCheckedKeys([])
    },
    getcheckedKeys (menus) {
      menus.forEach(menu => {
        if (!menu.selected) {
          return
        }
        if (menu.menuIdList && !menu.selected) {
          return this.getcheckedKeys(menu.menuIdList)
        }
        this.checkedKeys = [...this.checkedKeys, menu.id]
      })
    },
    async loadRoleMenu () {
      const { data } = await getRoleMenus(this.roleId)
      if (data.code === '000000') {
        this.getcheckedKeys(data.data)
      }
    },
    async getListMenu () {
      const { data } = await getMenuList()
      if (data.code === '000000') {
        this.menu = data.data
      }
    },
    async onSave () {
      const { data } = await setMenuList({
        roleId: this.roleId,
        menuIdList: this.$refs['menu-tree'].getCheckedKeys()
      })
      if (data.code === '000000') {
        this.$message.success('操作成功')
        this.$router.push({
          name: 'role'
        })
      }
    }
  }
}
</script>

<style lang='sccss' scoped>
</style>
